package sealte.wdgf.system.listener;

import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sealte.wdgf.model.system.DataSourceObject;
import sealte.wdgf.model.system.HTMLConfigObject;
import sealte.wdgf.model.system.SessionMapObject;
import sealte.wdgf.system.config.DatabaseInfoReader;
import sealte.wdgf.system.config.HTMLConfigReader;

public class ApplicationContextListener implements ServletContextListener {
	
	static{
		setProperties();
	}
	
	private static Logger logger = LoggerFactory.getLogger(ApplicationContextListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext application = sce.getServletContext();
		BasicDataSource ds = (BasicDataSource)application.getAttribute("DataSource");
		try {
			if(null!=ds){
				ds.close();
			}
		} catch (SQLException e) {
			logger.error("ApplicationContextListener 数据源关闭失败！原因："+e.getMessage());
		}
		application.removeAttribute("DataSource");
		application.removeAttribute("SessionMap");
		application.removeAttribute("HTMLConfig");
		logger.info("ApplicationContextListener 停止工作！");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("ApplicationContextListener 开始工作！");
		ServletContext application = (ServletContext)sce.getServletContext();
		loadDataSourceObject(application);
		loadSessionMapObject(application);
		loadHTMLConfigObject(application);
	}
	
	private static void setProperties(){
		//为log4j.properties配置文件的变量${LOG_DIR}赋值
		String webInfPath = ApplicationContextListener.class.getResource("").getPath()
				+"../../../../../";
		System.setProperty("LOG_DIR", webInfPath+"logs");
	}
	
	private void loadDataSourceObject(ServletContext application){
		logger.info("ApplicationContextListener 开始加载DataSource对象！");
		DatabaseInfoReader dir = new DatabaseInfoReader();
		DataSourceObject dso = dir.getDataSourceObject();
		application.setAttribute("DataSource", dso.getDataSource());
	}
	
	private void loadSessionMapObject(ServletContext application){
		logger.info("ApplicationContextListener 开始加载SessionMap对象！");
		SessionMapObject smo = new SessionMapObject();
		application.setAttribute("SessionMap", smo);
	}
	
	private void loadHTMLConfigObject(ServletContext application){
		logger.info("ApplicationContextListener 开始加载HTMLConfig对象！");
		HTMLConfigReader hcr = new HTMLConfigReader();
		HTMLConfigObject hco = hcr.getConfigObject();
		application.setAttribute("HTMLConfig", hco);
	}
}
